<template>
  <div class="project-child-list">
    <ListTab v-if="!showMobilePage" :show-header="true" />
    <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="table-list min-fill-page">
      <dataDisplay
        :page-item="5"
        :data-list="[
          {data: orderStatistics.totalOrder, label: '总订单数', icon: icon_3, isMoney: false},
          {data: orderStatistics.totalPrice, label: '总订单金额', icon: icon_4},
          {data: orderStatistics.totalTaxCost, label: '总含税成本', icon: icon_5}
        ]"
        project-child
        class="mobile-data"
        style="margin-bottom:16px;"
      />
      <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
        <FilterTool
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          show-search-btn
          is-search-resource
          is-show-config
          @selectChange="handelFilterInputChange"
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus"/>
        <div class="opeator-bar">
          <createBtn v-if="hasRouteAuth('crm:projectChild:add') || isAdmin" style="margin-right:14px;" @click.native="createProjectChild" />
          <MoreOpeator
            ref="moreOpeatorRef"
            :list="[
              {label: '批量开启采集', handelClick: handleBatchPick, auth: hasRouteAuth('crm:projectChild:batchPick')},
              {label: '自定义列', handelClick: tableSettingOpen}
            ]"
            class="mr10"
          />
          <btnGroup
            ref="btnGroupRef"
            :list="[
              {label:'导入', handelClick:uploadDialogShow, auth: hasRouteAuth('crm:projectChild:importAdd') || hasRouteAuth('crm:projectChild:importEdit') },
              {label:'导出', type: 'export', auth: hasRouteAuth('crm:projectChild:listExport'), isBeforeExport:true, beforeExport:exportBeforeExport, refName:'exportRef', exportName:'项目渠道单', exportApi:'admin/project/child/list/export'},
            ]"
          />
        </div>
      </div>
      <div v-loading="listLoading" style="min-height: 300px;">
        <u-table
          v-if="list.items.length > 0"
          ref="tableRef"
          :data="list.items"
          :height="setTableHeight"
          :row-class-name="tableRowClassName"
          :row-height="49"
          :border="false"
          :key="tableKey"
          use-virtual
          class="fb-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
          @sort-change="sortMethod"
          @select="selectTable"
          @select-all="selectTable">
          <u-table-column
            align="center"
            fixed="left"
            type="selection"
            width="50"/>
          <template v-for="(settingItem) in tableSetting">
            <u-table-column
              v-if="settingItem.isShow && projectOrderProps[settingItem.fieldName]"
              :key="settingItem.fieldName"
              v-bind="projectOrderProps[settingItem.fieldName]"
            >
              <template slot-scope="scope">
                <!-- 订单编号 -->
                <template v-if="settingItem.fieldName === 'orderId'">
                  <el-tooltip v-if="scope.row.orderInfo.orderId" class="item" placement="top" effect="dark">
                    <div slot="content" style="max-width: 200px;">{{ scope.row.orderInfo.orderId }}</div>
                    <router-link
                      :to="{name: 'projectChildDetail', params: { id: scope.row.orderInfo.id }}"
                      target="_blank"
                      class="overflow ellipsis"
                      style="color:#406EFF"
                    >{{ scope.row.orderInfo.orderId }}</router-link>
                  </el-tooltip>
                  <div v-else>--</div>
                </template>
                <template v-else-if="projectOrderProps[settingItem.fieldName].showType === 'normal'">
                  <ToolTip :content="scope.row.orderInfo[settingItem.fieldName]"/>
                </template>
                <!-- 项目编号 -->
                <template v-else-if="settingItem.fieldName === 'projectNum'">
                  <ToolTip v-if="scope.row.projectNum" :content="scope.row[settingItem.fieldName]">
                    <router-link
                      :to="{name: 'projectDetail', params: { id: scope.row.projectId }}"
                      class="overflow ellipsis"
                      style="color:#406EFF"
                    >{{ scope.row.projectNum }}</router-link>
                  </ToolTip>
                  <div v-else>--</div>
                </template>
                <!-- 下单日期 -->
                <template v-else-if="settingItem.fieldName === 'orderTime'">
                  <div v-if="scope.row.orderInfo.orderTime">{{ scope.row.orderInfo.orderTime | standardFormatNoHour('YYYY/MM/DD') }}</div>
                  <div v-else>--</div>
                </template>
                <!-- 项目名称 -->
                <template v-else-if="settingItem.fieldName === 'projectName'">
                  <el-tooltip v-if="scope.row.projectName" class="item" placement="top" effect="dark">
                    <div slot="content" style="max-width: 200px;">{{ scope.row.projectName }}</div>
                    <router-link
                      :to="{name: 'projectDetail', params: { id: scope.row.projectId }}"
                      target="_blank"
                      class="overflow ellipsis"
                      style="color:#406EFF"
                    >{{ scope.row.projectName }}</router-link>
                  </el-tooltip>
                  <div v-else>--</div>
                </template>
                <!-- 备注 -->
                <template v-else-if="settingItem.fieldName === 'remark'">
                  <div v-if="scope.row.orderInfo.remark" style="max-width: 100%;" >
                    <el-tooltip placement="top">
                      <div slot="content" style="max-width:200px">{{ scope.row.orderInfo.remark }}</div>
                      <div class="overflow" style="display:inline-block;">{{ scope.row.orderInfo.remark }}</div>
                    </el-tooltip>
                  </div>
                  <div v-else>--</div>
                </template>
                <!-- 含税金额(元) -->
                <template v-else-if="settingItem.fieldName === 'taxAmount'">
                  <PriceColumn :real-val="scope.row.orderInfo.taxAmount" :price="scope.row.orderInfo.taxAmount / 100" />
                </template>
                <!-- 含税成本(元) -->
                <template v-else-if="settingItem.fieldName === 'cost'">
                  <PriceColumn :real-val="scope.row.orderInfo.cost" :price="scope.row.orderInfo.cost / 100" />
                </template>
                <!-- 是否开启采集 -->
                <template v-else-if="settingItem.fieldName === 'isPicked'">
                  <div v-if="scope.row.orderInfo && typeof scope.row.orderInfo.isPicked === 'boolean'">{{ scope.row.orderInfo.isPicked ? '是' : '否' }}</div>
                  <div v-else>--</div>
                </template>
                <!-- 刊例价(元) -->
                <template v-else-if="settingItem.fieldName === 'articlesPrice'">
                  <PriceColumn :real-val="scope.row.orderInfo.articlesPrice" :price="scope.row.orderInfo.articlesPrice / 100" />
                </template>
                <!-- 所属部门 -->
                <template v-else-if="settingItem.fieldName === 'attributionMatrixName'">
                  <el-tooltip v-if="scope.row.orderInfo.attributionMatrixName" placement="top">
                    <div slot="content" style="max-width:200px">
                      {{ (scope.row.orderInfo.attributionMatrixFullName || scope.row.orderInfo.attributionMatrixName) | getDeptFullName }}
                    </div>
                    <div class="overflow">{{ scope.row.orderInfo.attributionMatrixName }}</div>
                  </el-tooltip>
                  <div v-else>--</div>
                </template>
                <!-- 收入类型 -->
                <template v-else-if="settingItem.fieldName === 'incomeTypeStr'">
                  <div v-if="scope.row.orderInfo.incomeTypeStr || scope.row.orderInfo.incomeType === 0">{{ scope.row.orderInfo.incomeTypeStr }}</div>
                  <div v-else>--</div>
                </template>
                <!-- 下单平台 -->
                <template v-else-if="settingItem.fieldName === 'orderPlatform'">
                  <div class="flex-center">
                    <platformIcon :data="scope.row.orderInfo.orderPlatform" />
                    {{ scope.row.orderInfo.orderPlatform || '--' }}
                  </div>
                </template>
                <!-- 账号 -->
                <template v-else-if="settingItem.fieldName === 'dataAccount'">
                  <div class="flex-center">
                    <frameContent
                      v-if="scope.row.dataAccount"
                      ref="frameContent"
                      :platform="scope.row.orderInfo.orderPlatform"
                      :data-account="scope.row.dataAccount"
                      :url="scope.row.dataLink"
                      :account-id="scope.row.orderInfo.resourceId"
                      :account-name="scope.row.orderInfo.resourceName" />
                    <resource-info
                      v-if="scope.row.orderInfo.resourceName"
                      :resource-name="scope.row.orderInfo.resourceName"
                      :account-name-organization="scope.row.accountNameOrganization"
                      :account-name-platform="scope.row.accountNamePlatform"
                      :resource-id="scope.row.orderInfo.resourceCode"
                      style="max-width:calc(100% - 20px)"
                      account-belong-name="none"
                    />
                    <div v-else>--</div>
                  </div>
                </template>
                <!-- 执行人(商务侧) -->
                <template v-else-if="settingItem.fieldName === 'orderBusinessOperator'">
                  <CheckUserInfo
                    v-if="scope.row.orderInfo.orderBusinessOperator && scope.row.orderInfo.orderBusinessOperator.length"
                    :user-list="scope.row.orderInfo.orderBusinessOperator"
                    multiple
                  />
                  <div v-else>--</div>
                </template>
                <!-- 执行人(资源侧) -->
                <template v-else-if="settingItem.fieldName === 'orderResourceOperator'">
                  <CheckUserInfo
                    v-if="scope.row.orderInfo.orderResourceOperator && scope.row.orderInfo.orderResourceOperator.length"
                    :user-list="scope.row.orderInfo.orderResourceOperator"
                    multiple
                  />
                  <div v-else>--</div>
                </template>
                <template v-else-if="settingItem.fieldName === 'createName'">
                  <CheckUserInfo
                    v-if="scope.row.orderInfo.createUserId"
                    :user-id="scope.row.orderInfo.createUserId"
                    :label="scope.row.orderInfo.createName"
                  />
                  <div v-else>--</div>
                </template>
                <!-- 协作部门 -->
                <template v-else-if="settingItem.fieldName === 'cooperationDepartment'">
                  <ToolTip :content="handelArr(scope.row.orderInfo.cooperationDepartment, 'name', '/')" />
                </template>
                <!-- 标签 -->
                <template v-else-if="settingItem.fieldName === 'tag'">
                  <el-tooltip v-if="scope.row.orderInfo.tag && scope.row.orderInfo.tag.length" :open-delay="800" placement="top" effect="dark">
                    <div slot="content" style="max-width:300px">{{ handleStr(scope.row.orderInfo.tag) }}</div>
                    <div class="tag-wrap">
                      <span
                        v-for="(t,index) in handleTags(scope.row.orderInfo.tag)"
                        :key="index"
                        :style="t.color ? `color:${t.color};background:${changeColorAlphaVal(t.color, 0.14)}` : ''"
                        class="tag">
                        {{ t.name }}
                      </span>
                      <div v-if="scope.row.orderInfo.tag.length > 3">...</div>
                    </div>
                  </el-tooltip>
                  <div v-else>--</div>
                </template>
                <!-- 所属经营体 -->
                <template v-else-if="settingItem.fieldName === 'resourceAttributionMatrix'">
                  <el-tooltip v-if="scope.row.orderInfo.resourceAttributionMatrix" placement="top" effect="dark">
                    <div slot="content" style="max-width: 200px;">{{ scope.row.orderInfo.entityTip }}</div>
                    <div class="ellipsisOne">{{ scope.row.orderInfo.resourceAttributionMatrix }}</div>
                  </el-tooltip>
                  <span v-else>--</span>
                </template>
                <!-- 供应商类型 -->
                <template v-else-if="settingItem.fieldName === 'supplierType'">
                  <ToolTip v-if="scope.row.orderInfo.supplierType !== null" :content="scope.row.orderInfo.supplierType | getSupplierType" />
                  <span v-else>--</span>
                </template>
                <!-- 发布文案 -->
                <template v-else-if="settingItem.fieldName === 'publishInfo'">
                  <el-tooltip v-if="scope.row.publishInfo && scope.row.publishInfo.publishRemark" placement="top">
                    <div slot="content" style="max-width:200px">{{ scope.row.publishInfo.publishRemark }}</div>
                    <div class="overflow">{{ scope.row.publishInfo.publishRemark }}</div>
                  </el-tooltip>
                  <el-tooltip v-else-if="scope.row.orderInfo.content" placement="top">
                    <div slot="content" style="max-width:200px">{{ scope.row.orderInfo.content }}</div>
                    <div class="overflow">{{ scope.row.orderInfo.content }}</div>
                  </el-tooltip>
                  <div v-else>--</div>
                </template>
                <!-- 发布链接 -->
                <template v-else-if="settingItem.fieldName === 'orderLink'">
                  <div v-if="scope.row.orderInfo.orderLink">
                    <el-tooltip placement="top">
                      <div slot="content" style="max-width:200px">{{ scope.row.orderInfo.orderLink }}</div>
                      <a v-if="isLink(scope.row.orderInfo.orderLink)" :href="scope.row.orderInfo.orderLink" style="color: #406EFF;display:flex;align-items:center;cursor: pointer;" target="_blank"><i class="el-icon-link" />链接</a>
                      <div v-else class="overflow">{{ scope.row.orderInfo.orderLink }}</div>
                    </el-tooltip>
                  </div>
                  <div v-else>--</div>
                </template>
                <!-- 销售 -->
                <template v-else-if="settingItem.fieldName === 'clientInfo'">
                  <CheckUserInfo v-if="scope.row.clientInfo && scope.row.clientInfo.market" :label="scope.row.clientInfo.market" :user-id="scope.row.clientInfo.marketId" />
                  <span v-else>--</span>
                </template>
                <!-- 成本项 -->
                <template v-else-if="settingItem.fieldName === 'costBreakdown'">
                  <dialogCostlist :cost-list="scope.row.costBreakdown.costList || []" :order-id="scope.row.id" :btn-text="`共${scope.row.costBreakdown.costList?scope.row.costBreakdown.costList.length:0}项成本`" />
                </template>
                <!-- 创建时间 -->
                <template v-else-if="settingItem.fieldName === 'createTime'">
                  {{ scope.row.orderInfo.createTime | standardFormatNoHour('YYYY/MM/DD') }}
                </template>
                <template v-else-if="settingItem.fieldName === 'clientName'">
                  <ToolTip :content="scope.row.clientName" />
                </template>
              </template>
            </u-table-column>
          </template>
          <u-table-column align="left" width="110" label="操作" fixed="right">
            <template slot-scope="scope">
              <div style="display:flex;">
                <div class="button-text" @click="toDetail(scope)">查看</div>
                <el-dropdown trigger="click">
                  <div class="button-text bl">
                    更多 <i class="el-icon-arrow-down"/>
                  </div>
                  <el-dropdown-menu slot="dropdown" style="margin-top:-10px;margin-right:15px;padding: 0;">
                    <el-dropdown-item style="width:100px;text-align: center" @click.native="toDetail(scope)">
                      <div>查看</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="isEditAuth(scope.row)" style="width:100px;text-align: center" @click.native="toEdit(scope)">
                      <div>编辑</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="(hasRouteAuth('crm:projectChild:del') || isAdmin)" style="width:100px;text-align: center" @click.native="toDeleted(scope)">
                      <div>删除</div>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </template>
          </u-table-column>
        </u-table>
        <empty-placeholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
        <el-pagination
          v-show="list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-row>
      <fixed-pagination v-show="list.total > 0 && !showMobilePage || showMobilePage">
        <template v-if="showMobilePage">
          <FilterTool
            ref="FilterToolRef"
            v-model="paramsObj"
            :filter-list="filterList"
            show-search-btn
            is-search-resource
            show-mobile-icon
            @selectChange="handelFilterInputChange"
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @filterTagStatus="filterTagStatus"/>
          <MoreOpeator
            v-if="hasRouteAuth('crm:projectChild:listExport') || hasRouteAuth('crm:projectChild:importAdd') || hasRouteAuth('crm:projectChild:importEdit')"
            ref="moreOpeatorRef"
            :list="[
              {label: '导出', beforeExport:exportBeforeExport, isBeforeExport:true, refName:'exportRef', type: 'export', exportName:'项目渠道单', auth: hasRouteAuth('crm:projectChild:listExport'), exportApi:'admin/project/child/list/export',},
              {label: '批量导入新增', type:'import', callback: fetchData, importApi:'admin/project/child/list/importAdd', auth: hasRouteAuth('crm:projectChild:importAdd')},
              {label: '批量导入编辑', type:'import', callback: fetchData, importApi:'admin/project/child/list/importEdit', auth: hasRouteAuth('crm:projectChild:importEdit')},
              {label: '批量开启采集', handelClick: handleBatchPick, auth: hasRouteAuth('crm:projectChild:batchPick')},
              {label: '自定义列', handelClick: tableSettingOpen}
            ]"
            show-mobile-icon
          />
          <createBtn v-if="hasRouteAuth('crm:projectChild:add') || isAdmin" mobile-table @click.native="createProjectChild" />
        </template>
        <template v-else>
          <div style="flex:1;">
            <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
          </div>
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </template>
      </fixed-pagination>
    </div>
    <orderSetting ref="orderSetting" :setting-type="'projectOrder'" :init-order-list="initProjectOrderList" @handelSubmit="getTableSetting"/>
    <UploadDialog ref="uploadDialogRef" :upload-config="uploadConfig" @uploadList="fetchData" />
  </div>
</template>
<script>
import orderSetting from '@/components/OrderList/orderSetting';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import FilterTool from '@/components/Tool/filter';
import ResourceInfo from '@/components/ResourceInfo';
import frameContent from '@/components/Common/frameContent';
import platformIcon from '@/components/Common/platformIcon';
import dialogCostlist from '@/components/OrderList/dialogComponent/dialogCostlist';
import ListTab from '@/components/ListTab';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import createBtn from '@/components/Common/baseComponent/createBtn';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import UploadDialog from '@/views/project/model/uploadDialog';
import { getIncomeType, platformList, orderFormList } from '@/api/select';
import { getProjectTypes, projectOrderTotal, getProjectChildOrder, deleteProjectOrder, batchPick } from '@/api/project';
import { getDepartmentAll, getTagAll, costList } from '@/api/config';
import { getOperateoptions } from '@/api/resource';
import { getOrderSetting } from '@/api/order';
import { standardFormatNoHour } from '@/filters/date';
import { getDeptFullName } from '@/filters/dept';
import { getSupplierType } from '@/filters/status';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
import { hasRouteAuth } from '@/utils/permission';
import { TAG_MODULES } from '@/utils/const';
import { mapState } from 'vuex';
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import projectEditAuth from '@/views/project/projectEditAuth';
import { initProjectOrderList, projectOrderProps } from '@/components/OrderList/settingData';
import icon_3 from '@/assets/dataDisplay/icon_3.png';
import icon_4 from '@/assets/dataDisplay/icon_4.png';
import icon_5 from '@/assets/dataDisplay/icon_5.png';
import setting from '@/assets/setting.png';
import { showModal } from '@/utils/message';
import { costSettlementStatusOption } from '@/views/order/model/selectData';
import { strJsonParse } from '@/utils/index';
import { changeColorAlphaVal } from '@/utils/tools';

export default {
  components: {
    orderSetting,
    EmptyPlaceholder,
    FilterTool,
    ResourceInfo,
    platformIcon, dialogCostlist, ListTab, dataDisplay, MoreOpeator, createBtn, btnGroup,
    frameContent, UploadDialog },
  filters: { standardFormatNoHour, getDeptFullName, getSupplierType },
  mixins: [tableSelections, projectEditAuth, TableAdaptive, mobileTable],
  data() {
    return {
      icon_3,
      icon_4,
      icon_5,
      setting,
      TAG_MODULES,
      initProjectOrderList, projectOrderProps, // 3.0.2自定义列
      tableRefName: 'tableRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      listLoading: false,
      opeatorLoading: false,
      screenWidth: document.body.clientWidth,
      orderStatistics: {},
      page: 1,
      perPage: 20,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      paramsObj: {},
      mediumBtnStyle: {
        fontSize: '12px',
        width: '100%',
        whiteSpace: 'nowrap',
        padding: '0',
        marginLeft: '0px',
        marginRight: '0px',
        height: '30px',
        lineHeight: '30px',
        border: 'none',
        borderRadius: '0'
      },
      projectTypeOption: [],
      incomeTypeOption: [],
      platformTypeOption: [],
      orderFormOption: [],
      deptTreeList: [],
      sortName: '',
      sortType: '',
      operateModeList: [], // 运营模式列表
      rangeKeyArr: [{
        attr: 'createTime',
        start: 'createStartTime',
        end: 'createEndTime',
        type: 'time',
        addTime: true
      }, {
        attr: 'orderTime',
        start: 'orderStartTime',
        end: 'orderEndTime',
        type: 'time'
      }, {
        attr: 'costTime',
        start: 'costStartTime',
        end: 'costEndTime',
        type: 'time'
      }],
      tagTreeList: [],
      isUmyTable: true,
      arrayKeyArr: ['costItem', 'departmentId', 'cooperationDepartment', 'operateMode', 'resourceAttributionMatrixId', 'tag', 'orderPlatformId'],
      supplierType: [{ label: '公司', value: 0 }, { label: '个人', value: 1 }],
      tableSetting: [],
      uploadConfig: [{
        id: 0,
        name: '导入新增',
        importApi: '/admin/project/child/list/importAdd',
        exportTitle: '导入模板',
        exportApi: 'admin/project/child/template/download',
        isShow: hasRouteAuth('crm:projectChild:importAdd')
      }, {
        id: 1,
        name: '导入编辑',
        importApi: '/admin/project/child/list/importEdit',
        exportTitle: '导入模板',
        exportApi: 'admin/project/child/template/download',
        isShow: hasRouteAuth('crm:projectChild:importEdit')
      }],
      costItemOptions: [],
      tableKey: 0
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    tableOutsideHeight() {
      if (this.showMobilePage) {
        return 214;
      }
      return 246;
    },
    filterList() {
      const arr = [
        // 输入框
        { keyword: 'orderId', name: '订单编号', type: 'input' },
        { keyword: 'projectNum', name: '项目编号', placeholder: '支持批量搜索，以","隔开即可', type: 'input', inputType: 'textarea' },
        { keyword: 'resourceName', name: '账号', type: 'input' },
        { keyword: 'supplier', name: '供应商', type: 'input' },
        { keyword: 'market', name: '销售', type: 'conditionInput', excludeKey: 'marketEqual' },
        { keyword: 'theme', name: '品牌名称', type: 'input' },
        { keyword: 'projectName', name: '项目名称', type: 'input' },
        { keyword: 'content', name: '文案内容', type: 'input' },
        { keyword: 'resourceCode', name: '账号ID', type: 'input' },
        { keyword: 'systemId', name: '系统ID', type: 'input' },
        { keyword: 'cooperation', name: '合作运营方', type: 'input' },
        { keyword: 'orderOperator', name: '执行人', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { keyword: 'orderBusinessOperator', name: '执行人(商务侧)', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { keyword: 'orderResourceOperator', name: '执行人(资源侧)', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { keyword: 'creator', name: '创建人', type: 'input' },
        { keyword: 'accountOperationList', name: '所有人员', type: 'input' },
        { keyword: 'clientName', name: '客户名称', type: 'input', placeholder: '支持分号搜索多个', disabled: !hasRouteAuth('crm:projectInfo:clientInfo') },
        { keyword: 'remark', name: '备注', type: 'input' },
        // 下拉
        { keyword: 'isPicked', name: '是否开启采集', type: 'select', options: [{ value: 1, label: '是' }, { value: 0, label: '否' }] },
        { keyword: 'departmentId', name: '所属部门', type: 'cascaderSelectWithChild', childrenVal: 'children',
          options: this.deptTreeList },
        { keyword: 'cooperationDepartment', name: '协作部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'projectType', name: '项目类型', type: 'select', options: this.projectTypeOption },
        { keyword: 'incomeType', name: '收入类型', type: 'select', options: this.incomeTypeOption },
        { keyword: 'orderPlatformId', name: '下单平台', type: 'mulSelect', options: this.platformTypeOption },
        { keyword: 'orderFormId', name: '下单形式', type: 'select', emptyText: '请先选择下单平台', options: this.orderFormOption },
        { keyword: 'operateMode', name: '运营模式', valueName: 'value', labelName: 'label', multiple: true, collapseTags: true,
          childrenVal: 'children', type: 'cascaderSelect', checkStrictly: false, options: this.operateModeList },
        { keyword: 'resourceAttributionMatrixId', name: '所属经营体', type: 'conditionSelect', selectType: 'cascaderSelectWithChild', excludeKey: 'resourceAttributionMatrixIdEqual',
          childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'supplierType', name: '供应商类型', type: 'select', options: this.supplierType },
        { keyword: 'tag', name: '标签', valueName: 'name', labelName: 'name', childrenVal: 'item', type: 'cascaderSelect',
          checkStrictly: false, options: this.tagTreeList, multiple: true, filterable: true, collapseTags: true },
        { keyword: 'costSettleStatus', name: '成本结算', type: 'select', options: costSettlementStatusOption },
        { keyword: 'costItem', name: '成本项', type: 'mulSelect', options: this.costItemOptions },
        // 日期
        { keyword: 'orderTime', name: '下单日期', timeType: 'daterange', type: 'rangeDate', format: 'yyyy/MM/dd' },
        { keyword: 'createTime', name: '创建时间', timeType: 'daterange', type: 'rangeDate', format: 'yyyy/MM/dd' },
        { keyword: 'costTime', name: '成本创建时间', timeType: 'daterange', type: 'rangeDate' }
      ];
      return arr;
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'editProjectChild' || from.name === 'projectChildDetail') {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    next();
  },
  activated() {
    if (!this.$route.meta.isChange) {
      this.paramsObj = {};
      // 从智能结算跳到订单列表需要筛选的参数
      const jumpOrderParams = strJsonParse(localStorage.getItem('jumpOrderParams'));
      if (jumpOrderParams) {
        localStorage.removeItem('jumpOrderParams');
        Object.keys(jumpOrderParams).forEach(key => {
          this.$set(this.paramsObj, key, jumpOrderParams[key]);
        });
      }
      const hasDefaultPresetFilter = this.$refs.FilterToolRef && this.$refs.FilterToolRef.hasDefaultPresetFilter;
      if (this.$route.query.executor) {
        this.$set(this.paramsObj, 'executor', this.$route.query.executor);
      }
      // 当预设的默认筛选且为第一次进入页面时，不请求数据（会在 filterTool 组件进行筛选）
      if (!this.list.isInit || !hasDefaultPresetFilter) {
        if (this.clearMixinSelection) this.clearMixinSelection();
        if (this.$route.params && this.$route.params.projectNums) {
          this.$set(this.paramsObj, 'projectNum', this.$route.params.projectNums);
        }
        this.fetchData(true);
      }
    } else {
      if (this.list && this.list.items && this.list.items.length === 0) {
        this.fetchData(true);
      } else {
        this.fetchData();
      }
    }
    this.projectTypeOption = [];
    this.incomeTypeOption = [];
    this.platformTypeOption = [];
    this.queryDeptTreeList();
    this.projectTypeList();
    this.incomeTypeList();
    this.platformTypeList();
    this.getOperate();
    this.queryTagTreeList();
    this.getTableSetting();
    this.costItemList();
  },
  methods: {
    hasRouteAuth,
    changeColorAlphaVal,
    /* 下拉框选项 START */
    // 所属部门
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    // 获取项目类型
    async projectTypeList() {
      this.projectTypeOption.push({ value: -1, label: '全部' });
      try {
        const result = await getProjectTypes({ type: 2 });
        const projectOption = result.data.map(item => {
          return {
            value: item.id,
            label: item.name
          };
        });
        this.projectTypeOption.push(...projectOption);
      } catch (error) {
        console.log(error);
      }
    },
    // 获取收入类型的列表
    async incomeTypeList() {
      this.incomeTypeOption.push({ value: -1, label: '全部' });
      try {
        const result = await getIncomeType();
        const incomeOption = result.data.map(item => {
          return {
            value: item.id,
            label: item.name
          };
        });
        this.incomeTypeOption.push(...incomeOption);
      } catch (error) {
        console.log(error);
      }
    },
    // 获取下单平台选项
    async platformTypeList() {
      this.platformTypeOption.push({ value: -1, label: '全部' });
      try {
        const result = await platformList();
        const option = result.data.map(item => {
          return {
            value: item.id,
            label: item.value
          };
        });
        this.platformTypeOption.push(...option);
      } catch (error) {
        console.log(error);
      }
    },
    // 获取下单形式
    async getOrderForm() {
      let orderPlatformId;
      if (this.paramsObj.orderPlatformId && Array.isArray(this.paramsObj.orderPlatformId)) {
        orderPlatformId = this.paramsObj.orderPlatformId.join(',');
      }
      if (!orderPlatformId) { return; }
      try {
        const result = await orderFormList(orderPlatformId);
        if (result.data && result.data.length > 0) {
          result.data.forEach(i => {
            i.label = i.value;
            i.value = i.id;
          });
        }
        this.orderFormOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    handleBatchPick() {
      if (!this.multipleSelectionAll.length) {
        this.$message.warning('请选择需要开启采集的订单');
        return;
      }
      const canSelectRes = this.multipleSelectionAll.every(item => {
        return ['微信', '微博', '小红书'].includes(item.orderInfo.orderPlatform);
      });
      if (!canSelectRes) {
        this.$message.warning('仅微信、微博、小红书平台订单可开启采集');
        return;
      }
      showModal('确认开启采集？', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        type: 'warning',
        customClass: ' del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        const ids = this.multipleSelectionAll.map(item => item.id).join(',');
        batchPick({ ids }).then(res => {
          if (res.code === 200) {
            this.$message.success('操作成功');
            if (this.clearMixinSelection) this.clearMixinSelection();
            this.fetchData();
          }
        }).catch(err => console.error(err));
      });
    },
    // 获取运营模式的列表
    getOperate() {
      getOperateoptions().then(res => {
        this.operateModeList = res.data;
      });
    },
    queryTagTreeList() {
      const params = { type: this.TAG_MODULES.RESOURCE };
      getTagAll(params).then(res => {
        this.tagTreeList = (res && res.data) || [];
        this.tagTreeList.forEach(item => {
          if (!item.item) item.disabled = true;
        });
      }).catch(e => {
        console.log(e);
      });
    },
    authControl() {
      if (!hasRouteAuth('crm:projectInfo:clientInfo')) {
        // 如果没有客户信息权限，移除客户名称
        this.tableSetting = this.tableSetting.filter(i => {
          return i.fieldName !== 'clientName';
        });
      }
    },
    /** 下拉选项 END */
    getTableSetting() {
      this.listLoading = true;
      getOrderSetting().then((res) => {
        let tableSetting = [];
        this.tableSetting = [];
        if (res.code === 200 && res.data && res.data.projectOrder) {
          tableSetting = this.jsonParse(res.data.projectOrder);
        } else {
          tableSetting = JSON.parse(JSON.stringify(initProjectOrderList));
        }
        this.$nextTick(() => {
          this.tableSetting = tableSetting;
          this.authControl();
          this.$forceUpdate();
        });
        this.tableKey++;
      }).catch(err => {
        this.listLoading = false;
        console.log(err);
      });
    },
    tableSettingOpen() {
      this.$refs.orderSetting.openDialog(this.tableSetting);
    },
    getParams() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      params.page = this.page;
      params.perPage = this.perPage;
      params.sortName = this.sortName;
      params.sortType = this.sortType;
      return params;
    },
    handelFilterInputChange({ value, item }) {
      if (item.keyword === 'orderPlatformId') {
        this.$set(this.paramsObj, 'orderFormId', '');
        this.getOrderForm();
      }
    },
    jsonParse(str) {
      if (typeof str !== 'string') return str;
      try {
        return JSON.parse(str);
      } catch (error) {
        return JSON.parse(JSON.stringify(initProjectOrderList));
      }
    },
    isLink(str) {
      const reg = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)([A-Za-z0-9-~]+)/;
      return reg.test(str);
    },
    handleTags(tag) {
      if (!Array.isArray(tag) || tag.length === 0) {
        return;
      }
      return tag.slice(0, 3);
    },
    handleStr(tag) {
      if (!Array.isArray(tag) || tag.length === 0) {
        return;
      }
      return tag.map(t => t.name).join();
    },
    handelArr(list, key, division) {
      if (!list || list.length === 0) return '--';
      return list.map(i => i[key]).join(division);
    },
    async getOrderTotal() {
      try {
        const params = this.getParams();
        const res = await projectOrderTotal(params);
        if (res.code === 200) {
          this.orderStatistics = res.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      this.getOrderTotal();
      const params = this.getParams();
      this.listLoading = true;
      getProjectChildOrder(params).then(({ data }) => {
        this.list = data;
        this.list.isInit = false;
        this.listLoading = false;
        if (this.setSelectRow) this.setSelectRow(data.items);
      }, result => {
        this.listLoading = false;
      }).catch(e => {
        console.error(e);
      });
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    queryClick() {
      if (this.list.isInit && this.$route.params && this.$route.params.projectNums) {
        this.$set(this.paramsObj, 'projectNum', this.$route.params.projectNums);
      }
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      if (this.clearMixinSelection) this.clearMixinSelection();
      this.queryClick();
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    createProjectChild() {
      this.$router.push({ name: 'createProjectChild' });
    },
    exportBeforeExport() { // 导出
      const params = this.getParams();
      const selectOrder = this.multipleSelectionAll || [];
      const ids = selectOrder.map(i => i.id);
      params.ids = ids.join(',');
      let msg = '<div>是否确定导出数据？</div>';
      if (!params.ids) {
        msg = msg + `<div style="color: red;font-size: 14px;">单次最多导出5000条</div>`;
      }

      if (!this.showMobilePage && this.$refs.btnGroupRef) {
        this.$refs.btnGroupRef.btnExport(params, msg);
      } else if (this.showMobilePage && this.$refs.moreOpeatorRef) {
        this.$refs.moreOpeatorRef.btnExport(params, 'exportRef', msg);
      }
    },
    toEdit(scope) { // 编辑
      const url = this.$router.resolve({
        name: 'editProjectChild',
        params: { id: scope.row.orderInfo.id }
      });
      window.open(url.href, '_blank');
    },
    toDetail(scope) {
      const url = this.$router.resolve({
        name: 'projectChildDetail',
        params: { id: scope.row.orderInfo.id }
      });
      window.open(url.href, '_blank');
    },
    toDeleted(scope) {
      const id = scope.row.orderInfo.id;
      showModal('是否确定删除该订单', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        type: 'warning',
        customClass: ' del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        deleteProjectOrder(id).then(res => {
          this.$message.success('删除成功');
          this.fetchData();
        }, result => {
          // this.$message.error(result.message);
        }).catch(err => {
          console.error(err);
        });
      });
    },
    uploadDialogShow() {
      this.$refs['uploadDialogRef'].dialogShow();
    },
    // 获取成本项列表
    async costItemList() {
      try {
        const params = { page: 1, perPage: 100, costBelong: 5 };
        const result = await costList(params);
        if (result.data) {
          result.data.items.forEach(i => {
            i.value = i.costId;
            i.label = i.costName;
          });
          this.costItemOptions = result.data.items;
        }
      } catch (error) {
        console.log(error);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.project-child-list {
  .table-list {
    margin: 16px 16px 0;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
  }
  .overflow {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 100%;
  }
  .tag-wrap{
    display: flex;
    align-items: center;
    .tag{
      color:#406EFF;
      background: #eff4ff;
      display: inline-block;
      max-width: 60px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      height: 20px;
      line-height: 20px;
      font-size: 12px;
      padding: 0px 8px;
      border-radius: 4px;
      margin-right: 4px;
    }
  }
}
.opeator-bar {
  position: absolute;
  right: 0;
  top: 0;
  display: flex;
  align-items: center;
}
.mr10 {
  margin-right: 10px;
}
</style>

